package utility

import (
	"context"
	"donkey-admin/internal/model/entity"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

type JwtCustClaims struct {
	UserInfo entity.SysUser
	jwt.RegisteredClaims
}

func GenerateToken(ctx context.Context, user entity.SysUser) (string, error) {
	TokenExpire, err := g.Config().Get(ctx, "jwt.TokenExpire")
	if err != nil {
		return "", err
	}

	SigningKey, err := g.Config().Get(ctx, "jwt.SigningKey")
	if err != nil {
		return "", err
	}

	iJwtCustClaims := JwtCustClaims{
		UserInfo: user,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "shop",
			Subject:   "shop",
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(TokenExpire.Duration())), //过期时间
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, iJwtCustClaims)

	return token.SignedString(SigningKey.Bytes())
}

func ParseToken(ctx context.Context, token string) (JwtCustClaims, error) {
	SigningKey, err := g.Config().Get(ctx, "jwt.SigningKey")
	iJwtCustClaims := JwtCustClaims{}
	claims, err := jwt.ParseWithClaims(token, &iJwtCustClaims, func(token *jwt.Token) (interface{}, error) {
		return SigningKey.Bytes(), nil
	})
	if err == nil && !claims.Valid {
		err = gerror.New("is not token")
	}
	return iJwtCustClaims, err
}
